package com.msb.mall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.msb.common.utils.HttpUtils;
import com.msb.mall.member.entity.MemberLevelEntity;
import com.msb.mall.member.exception.PhoneExistException;
import com.msb.mall.member.exception.UsernameExistException;
import com.msb.mall.member.service.MemberLevelService;
import com.msb.mall.member.vo.MemberLoginVO;
import com.msb.mall.member.vo.MemberReigerVO;
import com.msb.mall.member.vo.SocialUser;
import org.apache.catalina.webresources.war.WarURLConnection;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.common.utils.PageUtils;
import com.msb.common.utils.Query;

import com.msb.mall.member.dao.MemberDao;
import com.msb.mall.member.entity.MemberEntity;
import com.msb.mall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }


    /**
     * 完成会员的注册功能
     *
     * @param vo
     */
    @Override
    public void register(MemberReigerVO vo) throws PhoneExistException, UsernameExistException {
        MemberEntity member = new MemberEntity();

        //设置默认会员等级
        MemberLevelEntity defaultMemberLevel = memberLevelService.queryMemberLevelDefault();
        member.setLevelId(defaultMemberLevel.getId());

        // 账号和手机号不能重复
        //校验
        checkUsernameUnique(vo.getUserName());
        checkPhoneUnique(vo.getPhone());
        //设置值
        member.setUsername(vo.getUserName());
        member.setMobile(vo.getPhone());

        //加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        member.setPassword(encoder.encode(vo.getPassword()));

        //其他的默认值
        member.setCreateTime(new Date());


        this.save(member);
    }

    /**
     * 登录
     *
     * @param vo
     * @return
     */
    @Override
    public MemberEntity login(MemberLoginVO vo) {

        //根据账号获取手机号查询会员信息
        MemberEntity member = this.getOne(new QueryWrapper<MemberEntity>().eq("username", vo.getUserName()).or().eq("mobile", vo.getUserName()));
        if (member != null) {
            //存在  对比密码 校验
            BCryptPasswordEncoder en = new BCryptPasswordEncoder();
            boolean matches = en.matches(vo.getPassword(), member.getPassword());
            if (matches) {
                //登录成功
                return member;
            }
        }
        return null;
    }


    /**
     * 社交登录
     * @param vo
     * @return
     */
    @Override
    public MemberEntity socialLogin(SocialUser vo) {
        MemberEntity memberEntity = this.getOne(new QueryWrapper<MemberEntity>().eq("social_uid", vo.getUid()));
        if (memberEntity != null) {
            //如过不是第一次社交登录, 那么就更新相关信息  token和过期时间
            MemberEntity member = new MemberEntity();
            member.setId(memberEntity.getId());
            member.setAccessToken(vo.getAccessToken());
            member.setExpiresIn(vo.getExpiresIn());

            this.updateById(member);

            //返回完整的登录信息
            memberEntity.setAccessToken(vo.getAccessToken());
            memberEntity.setExpiresIn(vo.getExpiresIn());
            return memberEntity;
        }
            // 如果用户是第一次社交登录  那么需要注册
        MemberEntity memberReg = new MemberEntity();
        memberReg.setAccessToken(vo.getAccessToken());
        memberReg.setExpiresIn(vo.getExpiresIn());
        memberReg.setSocialUid(vo.getUid());

        //通过token调用微博接口  获取用户信息
        try {
            Map<String, String> querys = new HashMap<>();
            querys.put("access_token", vo.getAccessToken());
            querys.put("uid", vo.getUid());

            HttpResponse response = HttpUtils.doGet("http://api.weibo.com",
                    "2/users/show.json",
                    "get",
                    new HashMap<>(),
                    querys);

            if (response.getStatusLine().getStatusCode() == 200) {
                String json = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(json);
                String screenName = jsonObject.getString("screen_name");
                String gender = jsonObject.getString("gender");

                memberReg.setGender("m".equals(gender) ? 1 : 0);
                memberReg.setNickname(screenName);
            }

        } catch (Exception e) {

        }

        this.save(memberReg);

        return memberReg;
    }


    /**
     * 校验手机号是否存在
     *
     * @param phone
     * @throws PhoneExistException
     */
    private void checkPhoneUnique(String phone) throws PhoneExistException {
        int count = this.count(new QueryWrapper<MemberEntity>().eq("mobile", phone));

        if (count > 0) {
            throw new PhoneExistException();
        }
    }

    /**
     * 校验用户名是否存在
     *
     * @param userName
     * @throws UsernameExistException
     */
    private void checkUsernameUnique(String userName) throws UsernameExistException {
        int count = this.count(new QueryWrapper<MemberEntity>().eq("username", userName));

        if (count > 0) {
            throw new UsernameExistException();
        }

    }

}